package com.example.soscall.activity;

import androidx.lifecycle.ViewModel;

import com.ecarx.common.BaseActivity;
import com.ecarx.common.SharedViewModel;
import com.ecarx.xui.adaptapi.oncall.Call;
import com.example.soscall.BR;
import com.example.soscall.R;
import com.example.soscall.PhoneLiveData;
import com.example.soscall.databinding.ActivityCallBinding;
import com.example.soscall.databinding.ActivityMainBinding;
import com.example.soscall.utils.CallHelper;
import com.example.soscall.utils.RxUtils;
import com.example.soscall.utils.TimeUtil;

import java.util.concurrent.TimeUnit;

import io.reactivex.disposables.Disposable;

public class CallActivity extends BaseActivity<PhoneLiveData, ActivityCallBinding> {
    protected boolean mStopTimeHandle = false;
    private Disposable timeIntervel;
    private int seconds;
    @Override
    protected int getLayoutResId() {
        return  R.layout.activity_call;
    }

    @Override
    protected void initView() {
        mViewModel.getPhoneState().observeForever((state) ->{
            switch (state) {
                case Call.CALL_STATUS_OFFHOOK:
                    mStopTimeHandle = false;
                    int seconds;
                    if (CallHelper.getInstance().getCallDuration() > -1) {
                        seconds = CallHelper.getInstance().getCallDuration();
                    } else {
                        seconds = CallHelper.getInstance().getmCallSeconds() + 1;
                    }
                    mViewModel.setDuringSecond(TimeUtil.formatCallTime(seconds));
                    startTime();
                    break;
                case Call.CALL_STATUS_END:
                    stopTime();
                    break;
            }
        });

    }


    public void stopTime() {
        mStopTimeHandle = true;
        if (timeIntervel != null) {
            timeIntervel.dispose();
            timeIntervel = null;
        }
    }

    private void startTime() {
        this.seconds = 0;
        if(timeIntervel!=null){
            return;
        }
        timeIntervel = RxUtils.intervel(1, TimeUnit.SECONDS, (result, data) -> {
            if (mStopTimeHandle) {
                return;
            }
            seconds++;
            if (mViewModel != null) {
//                if (CallHelper.getInstance().getCallDuration() > 0) {
//                   int seconds = CallHelper.getInstance().getCallDuration();
                mViewModel.setDuringSecond(TimeUtil.formatCallTime(seconds));

//                setStateText(TimeUtil.formatCallTime(seconds));
            }
        });
    }

    @Override
    protected <V extends ViewModel> V getViewModel() {
        return (V) getAppViewModelProvider().get(PhoneLiveData.class);
    }

    @Override
    protected int getViewModelId() {
        return BR.viewmodel;
    }
}
